﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.CodeDom.Compiler;
using System.Linq;
using System.Collections;
using System.IO;
using Microsoft.CSharp;
using Microsoft.JScript;
using Microsoft.VisualBasic;
using Microsoft.VisualC;

namespace vAddins
{
    internal class Builder
    {
        internal static string[] NotResourcesExtensions = new string[] {
            ".cs",
            ".vb",
            ".dll",
            ".exe"
        };

        internal static Assembly Build(string folder, Language language, IEnumerable<string> references)
        {
            var files = new List<string>(Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories));

            CodeDomProvider codeProvider = null;

            switch (language)
            {
                case Language.VisualBasic:
                    codeProvider = new VBCodeProvider(Compiler.Options);
                    break;

                default:
                    codeProvider = new CSharpCodeProvider(Compiler.Options);
                    break;
            }

            CompilerParameters options = new CompilerParameters();
            options.GenerateExecutable = false;
            options.GenerateInMemory = true;

            foreach (var ff in files.Where(f => !NotResourcesExtensions.Contains(Path.GetExtension(f))))
                options.EmbeddedResources.Add(ff);

            //options.ReferencedAssemblies.Add(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), @"Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\Profile\Client\System.dll"));

            options.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().Location);
            foreach (var asRef in vAddinsEngine.MandatoryHostReferences)
                options.ReferencedAssemblies.Add(asRef);
            foreach (var asRef in references)
                options.ReferencedAssemblies.Add(asRef);

            CompilerResults result;
            result = codeProvider.CompileAssemblyFromFile(options, files.Where(f => f.ToLower().EndsWith(language == Language.VisualBasic ? ".vb" : ".cs")).ToArray());

            Compiler.LastErrors = result.Errors;

            if (result.Errors.HasErrors)
            {
                throw new Exception("Compiling the code has returned exceptions!\r\nCheck vAddins.CSharp.Compiler.LastErrors for details.");
            } 

            codeProvider.Dispose();

            return result.CompiledAssembly;
        }

        internal static Assembly SecondBuild(string path)
        {
            return null;
        }
    }
}
